/*Author: Rony Lahav (ID:043489889)*/

import java.util.Set;

/*Author: Rony Lahav (ID:043489889)*/

/**
 * Handles the command by executing each one by received order unless idleTime is bigger than 0
 */
public class CmdManager implements Runnable{

	/*if there's no idle time gets the next command and executes it*/
	public void run() {
		long currentTime;
		final_project.idleStartTime = System.currentTimeMillis();
		final_project.idleTime=0;
		while (!final_project.commandsList.isEmpty() && !final_project.isShutDown()){
			currentTime=System.currentTimeMillis();
			if ((final_project.idleStartTime+final_project.idleTime)<currentTime){
				ICmd cmd = final_project.commandsList.pollFirst();
				if (cmd!=null)
					cmd.executeCmd();
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		do {	//last command might by IDLE so we wait for it to end
			currentTime=System.currentTimeMillis();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {}
		} while (!((final_project.idleStartTime+final_project.idleTime)<currentTime));
		final_project.shutDown=true;	//peer run is over once all command are read
		killSmallTreads();
	}

	private void killSmallTreads() {
		Set<Long> set = final_project.livingThreads.keySet();
		try {
			for (Long key : set) {
				try {
					Thread thread = final_project.livingThreads.get(key);
					while (thread.isAlive() && thread.isAlive())
						thread.interrupt();
				} catch (Exception e) {}
			}
		} catch (Exception e) {}
		final_project.livingThreads.clear();
	}

}
